package com.example.springbootdemo.handler;

import com.alibaba.fastjson.JSONObject;
import com.example.springbootdemo.bean.response.ResponseInfo;
import com.example.springbootdemo.util.JwtTokenUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author H
 * @time 2022/1/30 22:51
 */
@Component
public class TokenLogoutHandler implements LogoutHandler {

    @Autowired
    private RedisTemplate redisTemplate;

    @SneakyThrows
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        // 从header里面获取token
        String authorization = request.getHeader("Authorization");
        // 从redis中删除token
        if (Objects.nonNull(authorization)){
            String token = authorization.replace("Bearer ", "");
            String username = JwtTokenUtils.getUsernameFromToken(token);
            redisTemplate.delete(username);
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(ResponseInfo.success()));
    }
}
